package com.sinry.common.utils.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class RedisTplUtils {

    private static RedisTemplate<Object, Object> redisTemplate;

    @Resource
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        RedisTplUtils.redisTemplate = redisTemplate;
    }

    public static <R> R ops(Function<RedisTemplate<Object, Object>, R> function) {
        return function.apply(redisTemplate);
    }

    public static <R> void set(String key, R value, Long expired) {
        String valueNew;
        if (!(value instanceof String)) {
            valueNew = JSON.toJSONString(value);
        } else {
            valueNew = (String) value;
        }
        ops(redis -> {
            redis.opsForValue().set(key, valueNew, expired, TimeUnit.SECONDS);
            return null;
        });
    }
}
